package com.eliota.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eliota.entity.Menu;
import com.eliota.entity.Role;
import com.eliota.entity.RoleMenu;
import com.eliota.mapper.RoleMapper;
import com.eliota.mapper.RoleMenuMapper;
import com.eliota.service.MenuService;
import com.eliota.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MG
 * @since 2023-03-28
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    public RoleMapper roleMapper;

    @Resource
    public RoleMenuMapper roleMenuMapper;

    @Resource
    public MenuService menuService;


    @Override
    public boolean deleteById(Integer id) {
        int i = roleMapper.deleteById(id);
        if(i != 0){
            return true;
        }else
            return false;
    }

    @Override
    public boolean deleteBathByIds(List<Integer> ids) {
        int len = ids.size();
        int i = roleMapper.deleteBatchIds(ids);
        return i != 0;
    }

    /**
     *
     * @param roleId
     * @param menuIds
     */
    @Transactional //事务注解，保证同时成功和失败
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        /*QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(roleMenuQueryWrapper);*/
        roleMenuMapper.deleteByRoleId(roleId);


        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        for (Integer menuId : menuIds) {
            Menu menu = menuService.getById(menuId);
            if(menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())){
                //子菜单没有父级id
                /*每条遍历赋值*/
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            /*每条遍历赋值*/
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {

        return roleMenuMapper.getMenuByRoleId(roleId);
    }


}
